package org.example;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: dings
 * Date: 2024-09-21
 * Time: 13:14
 */
public class Demo02_DataSource {

    public static void main(String[] args) {
        //1. 定义MySQL数据源对象（连接池）
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        //2. 设置数据库连接串
        mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/test2?characterEncoding=utf8" +
                "&allowPublicKeyRetrieval=true&useSSL=false");
        //用户
        mysqlDataSource.setUser("root");
        //密码
        mysqlDataSource.setPassword("111111");

        //定义JDBC的数据源对象
        DataSource dataSource = mysqlDataSource;

        //定义连接对象
        Connection connection = null;
        //定义预处理SQL执行对象
        PreparedStatement statement = null;
        //定义结果集对象
        ResultSet resultSet = null;

        try {
            //1. 通过数据源获得数据库连接对象
            connection = dataSource.getConnection();
            //定义要执行的SQL
            String sql = "select student_id, sn, name, mail, class_id from student where name = ?";
            Scanner scanner = new Scanner(System.in);
            //2. 获取预处理SQL执行对象
            statement = connection.prepareStatement(sql);
            //接收用户输入
            System.out.println("请输入要查询的学生的姓名：");
            String name = scanner.next();
            //3. 用真实值替换占位符
            statement.setString(1, name);
            //4. 执行SQL，获取结果集对象
            resultSet = statement.executeQuery();
            //迭代打印结果集
            while (resultSet.next()) {
                long stuId = resultSet.getLong(1);
                String stuSn = resultSet.getString(2);
                String stuName = resultSet.getString(3);
                String stuMail = resultSet.getString(4);
                long stuClassId = resultSet.getLong(5);
                System.out.println(MessageFormat.format("学生编号={0}, 学号={1}, 姓名={2}, 邮箱={3}, 班级编号={4}",
                        stuId, stuSn, stuName, stuMail, stuClassId));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            // 依次释放资源，关闭连接
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
